package com.dsg.aspect;


import com.dsg.common.constants.MessageConstants;
import com.dsg.common.dto.AjaxResult;
import com.dsg.common.util.DateUtils;
import com.dsg.common.util.SingletonLoginUtils;
import com.dsg.support.LeveldbAccess;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author rong
 */
@Aspect
@Component
@Slf4j
public class NoRepeatSubmitAspect {

    @Autowired
    private LeveldbAccess leveldbAccess;

    @Around("@annotation(noRepeatSubmit)")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint, NoRepeatSubmit noRepeatSubmit)
            throws Throwable {
        if (noRepeatSubmit != null) {
            // 類名
            String className = proceedingJoinPoint.getTarget().getClass().getName();
            // 方法名
            String methodName = proceedingJoinPoint.getSignature().getName();
            String key = SingletonLoginUtils.getSystemUserId() + "-" + className + "." + methodName;
            Date date = leveldbAccess.get(key);
            if (date != null) {
                double time = DateUtils.getDistanceOfTwoTime(date, new Date());
                if (noRepeatSubmit.seconds() > time) {
                    log.warn("**************** 重複提交 ****************" + time);
                    AjaxResult ajaxResult = new AjaxResult(MessageConstants.SSO_STATUS_REPEAT_SUBMIT);
                    return ajaxResult;
                } else {
                    leveldbAccess.put(key, new Date());
                }
            } else {
                leveldbAccess.put(key, new Date());
            }
        }
        return proceedingJoinPoint.proceed();
    }
}
